package com.atguigu.spzx.common.intercepter;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.constant.Constant;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserLoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token==null){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String userInfoJson = redisTemplate.opsForValue().get(Constant.REDIS_USER_LOGIN_TOKEN + token);
        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
        AuthContextUtil.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();

    }
}
